﻿using System;
using System.Linq;
using System.Collections.Generic;
using NHibernate.Cfg;
using NHibernate;


namespace epicenter2010.NH.Generic
{
    /// <summary>
    /// Repository
    /// bstack @ 08/09/2009
    /// </summary>
    public class Repository<TKey, TEntity>
    {
        private readonly ISessionFactory c_sessionFactory;


        /// <summary>
        /// Ctor
        /// </summary>
        public Repository()
        {
            this.c_sessionFactory = (new Configuration()).Configure().BuildSessionFactory();
        }


        /// <summary>
        /// Get by Id
        /// </summary>
        /// <param name="id">Id</param>
        public IList<TEntity> GetAll()
        {
            using (var _session = this.c_sessionFactory.OpenSession())
            {
                return _session.CreateCriteria(typeof(TEntity)).List<TEntity>();
            }
        }


        /// <summary>
        /// Get by Id
        /// </summary>
        /// <param name="id">Id</param>
        public TEntity GetById(
            TKey id)
        {
            using (var _session = this.c_sessionFactory.OpenSession())
            {
                return _session.CreateCriteria(typeof(TEntity))
               .Add(NHibernate.Criterion.Expression.Eq("Id", id))
               .UniqueResult<TEntity>();
            }
        }


        /// <summary>
        /// Save
        /// </summary>
        /// <param name="subject"></param>
        /// <returns></returns>
        public void Save(
            TEntity subject)
        {
            using (var _session = this.c_sessionFactory.OpenSession())
            {
				using (var _transaction = _session.BeginTransaction())
				{
					try
					{
						_session.SaveOrUpdate(subject);
						_transaction.Commit();
					}
					catch (Exception)
					{
						_transaction.Rollback();
						throw;
					}
				}
            }
        }
    }
}
